package com.windea.study.kotlin.game.tankwar2.core

import java.io.*
import javax.sound.sampled.*

//FIXME 可能会因为流关闭而引起异常
object Composer {
	fun play(soundPath: String) {
		doPlay(soundPath, false)
	}
	
	fun playLoop(soundPath: String) {
		doPlay(soundPath, true)
	}
	
	private fun doPlay(soundPath: String, loop: Boolean) {
		val clip = AudioSystem.getClip()
		clip?.let {
			val resourceAsStream = javaClass.getResourceAsStream("/$soundPath")
			val stream = AudioSystem.getAudioInputStream(BufferedInputStream(resourceAsStream))
			stream?.let {
				clip.addLineListener { event ->
					if(event.framePosition.toInt() == clip.frameLength) {
						clip.close()
					}
				}
				clip.open(stream)
				if(loop) clip.loop(-1)
				clip.start()
			}
		}
	}
}
